package com.qf.apigateway.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author
 */
@Component
public class TimeStampFilter extends ZuulFilter {

    private SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER+50;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        boolean zuulResponse = currentContext.sendZuulResponse();
        //根据前置过滤的结果来决定是否启用当前过滤器，前面拦截这个就不执行。
        return zuulResponse;
    }

    @Override
    public Object run() throws ZuulException {
        System.err.println("过滤器启用了");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //假如我们要求用户必须通过timestamp来传递时间
        String timestamp = request.getParameter("timestamp");
        //比如我们要求的是yyyy-MM-dd HH:mm:ss
        try {
            Date date = simpleDateFormat.parse(timestamp);
            long time = date.getTime();
            //获取到毫秒值
            //获取到请求中的时间,
            long currentTime = System.currentTimeMillis();
            //当前时间的毫秒值
            //计算时间差,如果超出阈值,拦截请求
            if (currentTime - time > 60000) {
                //假设我们约定有效期是1分钟
                currentContext.setSendZuulResponse(false);
                currentContext.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
                currentContext.setResponseBody("时间范围超出阈值");
            }
        } catch (ParseException e) {
            e.printStackTrace();
            currentContext.addZuulResponseHeader("content-Type","text/html;charset=utf-8");
            currentContext.setResponseBody("时间范围超出阈值");
        }

        return null;
    }
}
